import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.sql.*;
import javax.servlet.annotation.WebServlet;
import org.json.JSONObject;
import org.json.JSONArray; // 导入JSON库

@WebServlet("/list_book")
public class ListBook extends HttpServlet {

    private static final String URL = "jdbc:mysql://1.15.151.81:3306/linux_exam";
    private static final String USER = "root";
    private static final String PASSWORD = "1qaz@WSX#EDC";
    private static final String DRIVER_CLASS = "com.mysql.cj.jdbc.Driver";

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setHeader("Access-Control-Allow-Origin", "*");
        response.setHeader("Access-Control-Allow-Methods", "GET");
        response.setHeader("Access-Control-Allow-Headers", "Content-Type");

        response.setContentType("application/json;charset=UTF-8");
        PrintWriter out = response.getWriter();

        JSONArray jsonArray = listbook();
        out.print(jsonArray.toString());
    }

    public JSONArray listbook() {
        Connection conn = null;
        Statement stmt = null;
        ResultSet rs = null;
        JSONArray jsonArray = new JSONArray(); // 创建JSON数组对象

        try {
            Class.forName(DRIVER_CLASS);
            conn = DriverManager.getConnection(URL, USER, PASSWORD);
            stmt = conn.createStatement();
            String sql = "SELECT * FROM t_book";
            rs = stmt.executeQuery(sql);

            while (rs.next()) {
                JSONObject book = new JSONObject(); // 创建JSON对象
                book.put("number", rs.getString("number"));
                book.put("name", rs.getString("name"));
                book.put("author", rs.getString("author"));
                jsonArray.put(book); // 将书籍对象添加到JSON数组
            }
        } catch (Exception e) {
            e.printStackTrace();
            try {
                jsonArray.put(new JSONObject().put("status", "error").put("message", "Error occurred: " + e.getMessage()));
            } catch (Exception ex) {
                ex.printStackTrace();
            }
        } finally {
            try { if (rs != null) rs.close(); } catch (Exception e) { e.printStackTrace(); }
            try { if (stmt != null) stmt.close(); } catch (Exception e) { e.printStackTrace(); }
            try { if (conn != null) conn.close(); } catch (Exception e) { e.printStackTrace(); }
        }
        return jsonArray; // 返回JSON数组
    }
}
